package com.yunquan.ohana.ui.calendar.profiles.add

import android.app.Application
import android.os.Handler
import android.os.Looper
import androidx.databinding.ObservableArrayList
import androidx.databinding.ObservableField
import androidx.lifecycle.LifecycleOwner
import com.google.gson.Gson
import com.yunquan.ohana.BR
import com.yunquan.ohana.R
import com.yunquan.ohana.base.binding.command.BindingAction
import com.yunquan.ohana.base.binding.command.BindingCommand
import com.yunquan.ohana.base.bus.event.SingleLiveEvent
import com.yunquan.ohana.base.ui.BaseViewModel
import com.yunquan.ohana.entity.RoleEntity
import com.yunquan.ohana.http.BaseHttp
import com.yunquan.ohana.http.exception.ApiException
import com.yunquan.ohana.http.observer.BaseObserver
import com.yunquan.ohana.http.transformer.CommonTransformer
import com.yunquan.ohana.utils.ToastUtils
import com.yunquan.ohana.utils.Utils
import io.reactivex.rxjava3.disposables.Disposable
import me.tatarka.bindingcollectionadapter2.ItemBinding
import okhttp3.RequestBody.Companion.toRequestBody

class AddProfilesViewModel(application: Application) : BaseViewModel(application) {

    val ui = SingleLiveEvent<Int>()

    var mDeviceId: String? = null
    var userType: Boolean? = null
    var mRole: RoleEntity? = null

    val title = ObservableField<String>()
    val name = ObservableField<String>()
    val isShowDelete = ObservableField<Boolean>(true)
    val selectedColor = ObservableField<Int>()

    val items = ObservableArrayList<ColorItemViewModel<AddProfilesViewModel>>()
    val itemBinding = ItemBinding.of<ColorItemViewModel<AddProfilesViewModel>>(
        BR.colorItemViewModel,
        R.layout.item_select_color,
        )

    val onSaveClick = BindingCommand<Any>(object : BindingAction {
        override fun call() {
            if (mRole == null) {
                addRole()
            } else {
                editRole()
            }
        }
    })

    val onDeleteClick = BindingCommand<Any>(object : BindingAction {
        override fun call() {
            deleteRole()
        }
    })


    override fun onCreate(owner: LifecycleOwner) {
        super.onCreate(owner)
        items.add(ColorItemViewModel(this, Utils.instance.context.getColor(R.color.c_FF9932)))
        items.add(ColorItemViewModel(this, Utils.instance.context.getColor(R.color.c_31AEFD)))
        items.add(ColorItemViewModel(this, Utils.instance.context.getColor(R.color.c_B261FF)))
        items.add(ColorItemViewModel(this, Utils.instance.context.getColor(R.color.c_19E9A4)))
        items.add(ColorItemViewModel(this, Utils.instance.context.getColor(R.color.c_EFE231)))
        items.add(ColorItemViewModel(this, Utils.instance.context.getColor(R.color.c_FF6868)))
        items.add(ColorItemViewModel(this, Utils.instance.context.getColor(R.color.c_FF69B2)))
        items.add(ColorItemViewModel(this, Utils.instance.context.getColor(R.color.c_8AEF31)))
        items.add(ColorItemViewModel(this, Utils.instance.context.getColor(R.color.c_8C84FF)))
        items.add(ColorItemViewModel(this, Utils.instance.context.getColor(R.color.c_49E9E1)))
        if(mRole?.backgroundColor != null){
            items[mRole?.backgroundColor!!.toInt()].checked.set(true)
            selectedColor.set(items[mRole!!.backgroundColor!!.toInt()].color.get())
        } else {
            items[0].checked.set(true)
            selectedColor.set(items[0].color.get())
        }
    }

    private fun addRole() {
        val map = mutableMapOf<String, Any?>()
        map["deviceId"] = mDeviceId
        map["name"] = name.get()
        map["backgroundColor"] = items.indexOfFirst { it.checked.get() == true }

        val body = Gson().toJson(map).toRequestBody(BaseHttp.MEDIA_TYPE_JSON)
        BaseHttp.api.createDeviceRoleById(body)
            .compose(CommonTransformer())
            .subscribe(object : BaseObserver<RoleEntity>() {
                override fun onSubscribe(d: Disposable) {
                    super.onSubscribe(d)
                    showLoading()
                }

                override fun onSuccess(result: RoleEntity?) {
                    super.onSuccess(result)
                    if (result != null) {
                        ui.value = 0
                    } else {
                        ToastUtils.showShort(R.string.failed_to_add_role)
                    }
                }

                override fun onComplete() {
                    super.onComplete()
                    hideLoading()
                }
            })
    }

    private fun editRole() {
        val map = mutableMapOf<String, Any?>()
        map["id"] = mRole?.id
        map["name"] = name.get()
        map["backgroundColor"] = items.indexOfFirst { it.checked.get() == true }

        val body = Gson().toJson(map).toRequestBody(BaseHttp.MEDIA_TYPE_JSON)
        BaseHttp.api.updateRoleToColor(body)
            .compose(CommonTransformer())
            .subscribe(object : BaseObserver<Boolean>() {
                override fun onSubscribe(d: Disposable) {
                    super.onSubscribe(d)
                    showLoading()
                }

                override fun onSuccess(result: Boolean?) {
                    super.onSuccess(result)
                    if (result == true) {
                        ui.value = 0
                    } else {
                        ToastUtils.showShort(R.string.edit_role_failure)
                    }
                }

                override fun onComplete() {
                    super.onComplete()
                    hideLoading()
                }
            })
    }

    private fun deleteRole() {
        val map = mutableMapOf<String, Any?>()
        map["id"] = mRole?.id
        map["deviceId"] = mDeviceId

        val body = Gson().toJson(map).toRequestBody(BaseHttp.MEDIA_TYPE_JSON)
        BaseHttp.api.deleteDeviceRole(body)
            .compose(CommonTransformer())
            .subscribe(object : BaseObserver<Int>() {
                override fun onSubscribe(d: Disposable) {
                    super.onSubscribe(d)
                    showLoading()
                }

                override fun onSuccess(result: Int?) {
                    super.onSuccess(result)
                    //0：删除成功，1：角色有任务，2：角色有日程，3：未知,4：无法删除管理员角色
                    when (result) {
                        0 -> {
                            ToastUtils.showShort(R.string.delete_success)
                            Handler(Looper.getMainLooper()).postDelayed({
                                ui.value = 0
                            }, 500)
                        }

                        1 -> {
                            ToastUtils.showShort(R.string.characters_have_tasks)
                        }

                        2 -> {
                            ToastUtils.showShort(R.string.characters_have_schedules)
                        }

                        4 -> {
                            ToastUtils.showShort(R.string.the_administrator_role_cannot_be_deleted)
                        }

                        else -> {
                            ToastUtils.showShort(R.string.delete_failed)
                        }
                    }
                }

                override fun onError(e: ApiException) {
                    super.onError(e)
                    ToastUtils.showShort(R.string.delete_failed)
                }

                override fun onComplete() {
                    super.onComplete()
                    hideLoading()
                }
            })
    }
}